package com.itheima.Service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Mapper.ProductFavoriteMapper;
import com.itheima.Service.ProductFavoriteService;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.ProductFavorite;
import com.itheima.pojo.FavoriteQueryParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProductFavoriteServiceImpl implements ProductFavoriteService {

    @Autowired
    private ProductFavoriteMapper favoriteMapper;

    @Override
    @Transactional
    public void add(ProductFavorite pf) {
        // 检查是否已收藏
        if (!checkStatus(pf.getUserId(), pf.getProductId())) {
            ProductFavorite favorite = new ProductFavorite();
            favorite.setUserId(pf.getUserId());
            favorite.setProductId(pf.getProductId());
            favorite.setCreateTime(LocalDateTime.now());
            favoriteMapper.insert(favorite);
        }
    }

    @Override
    public void cancel(Integer userId, Integer productId) {
        favoriteMapper.delete(userId, productId);
    }

    @Override
    public void batchCancel(Integer userId, List<Integer> productIds) {
        favoriteMapper.batchDelete(userId, productIds);
    }

    @Override
    public PageResult<ProductFavorite> list(FavoriteQueryParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<ProductFavorite> favorites = favoriteMapper.list(param.getUserId());
        Page<ProductFavorite> page = (Page<ProductFavorite>) favorites;
        return new PageResult<>((int) page.getTotal(), favorites);
    }

    @Override
    public boolean checkStatus(Integer userId, Integer productId) {
        return favoriteMapper.countByUserAndProduct(userId, productId) > 0;
    }

    @Override
    public Map<Integer, Boolean> batchCheckStatus(Integer userId, List<Integer> productIds) {
        if (productIds == null || productIds.isEmpty()) {
            return new HashMap<>();
        }
        
        List<Integer> favoritedIds = favoriteMapper.listFavoritedIds(userId, productIds);
        
        // 构建结果映射
        return productIds.stream()
                .collect(Collectors.toMap(
                        id -> id,
                        id -> favoritedIds.contains(id),
                        (existing, replacement) -> existing
                ));
    }
}